/*
 * Copyright 2008 Jens Meiss
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package mtt.appoptions;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import mtt.menu.events.ShowMainMenuEvent;
import mtt.rms.dataObjects.ApplicationOptions;
import mtt.rms.recordstores.options.events.SetApplicationOptionsEvent;
import mtt.rms.recordstores.options.events.UpdateApplicationOptionsEvent;

import hmvc.j2me.events.IEvent;
import hmvc.j2me.events.TerminateEvent;
import hmvc.j2me.view.AView;

/**
 *
 *
 * @author jens.meiss
 */
public class ApplicationOptionsView extends AView {
	
	private Form form = new Form("MTT - Optionen");
	
	private TextField textFieldUrlSyncServer = new TextField("URL des SyncServers", "", 100, TextField.URL);
	
	private Command commandBack = new Command("zurück", Command.BACK, 0);
	
	private Command commandStore = new Command("speichern", Command.ITEM, 0);
	
	private ApplicationOptions applicationOptions;

	public void handleEvent(IEvent event) {
		
		if (event instanceof SetApplicationOptionsEvent) {
			SetApplicationOptionsEvent setApplicationOptionsEvent = (SetApplicationOptionsEvent) event;
			setApplicationOptions(setApplicationOptionsEvent.getApplicationOptions());
		}
		
	}

	private void setApplicationOptions(ApplicationOptions applicationOptions) {
		
		this.applicationOptions = applicationOptions;
		
		textFieldUrlSyncServer.setString(applicationOptions.getUrlSyncServer());
		
		
	}

	public void terminate() {
	}

	public void init() {
		
		form.append(textFieldUrlSyncServer);
		form.addCommand(commandBack);
		form.addCommand(commandStore);
		setDisplayAble(form);
	}

	public void registerEvents() {
		getController().register(SetApplicationOptionsEvent.class, this);
	}

	public void commandAction(Command c, Displayable d) {
		
		if (c == commandBack) {
			getController().fireEventUp(new ShowMainMenuEvent());
			getController().fireEventLocal(new TerminateEvent());
		} else if (c == commandStore) {
			getController().fireEventUp(new UpdateApplicationOptionsEvent(getApplicationOptions()));
		}
		
	}

	private ApplicationOptions getApplicationOptions() {
		
		applicationOptions.setUrlSyncServer(textFieldUrlSyncServer.getString());
		
		return applicationOptions;
	}

}
